import { createStore } from 'vuex';
// 使用vuex将进行数据存储，缺点：页面刷新后失效
export default createStore({
    state: {
        cartList: [], //购物车数据
        dingdan: [], //订单列表
        edit: true, //编辑按钮的状态，
        oderListed: [], //已完成的订单列表
        userAddress: [{
                id: 1001,
                name: '小明',
                tel: '13123456731',
                province: '黑龙江省',
                city: '哈尔滨市',
                county: '南岗区',
                addressDetail: 'asd',
                isDefault: true,
                areaCode: '110101',
            },
            {
                id: 1002,
                name: '张三',
                tel: '13123456731',
                province: '黑龙江省',
                city: '哈尔滨市',
                county: '香坊区',
                addressDetail: 'asd',
                isDefault: false,
                areaCode: '110101',
            },
        ],
    },
    mutations: {
        // 数据赋值：commit
        // 添加购物车
        ADDCART(state, value) {
            state.cartList = value;
        },
        // 结算，添加到订单
        BAY(state, value) {
            state.dingdan = value;
        },
        // 购物车删除
        DELETE(state, value) {
            state.cartList = value;
        },
        // 判断是否显示编辑
        EDIT(state, value) {
            if (value === 'delete') {
                state.edit = true;
            } else {
                state.edit = !state.edit
            }
        },
        // 生成订单
        // concat:连接两个字符串
        UPDATEORDER(state) {
            state.oderListed = state.oderListed.concat(state.dingdan)
        },
        // 新增地址
        ADDADDRESS(state, value) {
            state.userAddress.map(item => {
                if (value.isDefault) {
                    item.isDefault = false
                }
            });
            state.userAddress.push(value);
        },
        // 编辑地址
        CHANGEADDRESS(state, value) {
            state.userAddress = state.userAddress.map(item => {
                if (value.isDefault && item.id != value.id) {
                    item.isDefault = false
                }
                return item.id === value.id ? value : item;
            })
        },
        // 删除地址
        DELETEADDRESS(state, value) {
            state.userAddress = state.userAddress.filter(item => {
                return !(value.id === item.id)
            })
            if (value.isDefault && state.userAddress.length) {
                state.userAddress[0].isDefault = true
            }
        }

    },
    // 做逻辑处理、判断或ajax请求：disp
    actions: {}
})